﻿using RTW.OA.Models;
using RTW.OA.Servers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace RTW.OA.Controllers
{
    public class BaseController : Controller
    {
        /// <summary>
        /// 当前登录的用户属性
        /// </summary>
        public user CurrentUser { get; set; }



        /// <summary>
        /// 重新基类在Action执行之前的事情
        /// </summary>
        /// <param name="filterContext">重写方法的参数</param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {


            //得到用户登录的信息
            CurrentUser = Session["UserInfo"] as user;
            if (CurrentUser == null)
            {
                Response.Redirect("/Login/Index");//如果用户为空跳转到登录界面
                //return ;
            }
            //权限
            var permissions = CommServers.GetPermissions(CurrentUser.USER_ID.ToString());
            //当前访问的Controller
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            //当前访问的Action
            string actionName = filterContext.ActionDescriptor.ActionName;

            if (permissions != null)
            {
                var btnlist = new List<string>();
                
                foreach (var p in permissions) {
                    //1路由、2方法、3按钮
                    switch (p.TYPE)
                    {
                        //路由和方法同验证方法
                        case 1:

                        case 2:
                            if (controllerName == p.CONTROLLER)
                            {
                                if (actionName == p.ACTION)
                                {
                                    //目前测试阶段，反向权限（默认所以权限是开的，设定限制权限）
                                    filterContext.Result = new ContentResult()
                                    {
                                        Content = "您没有访问此功能的权限，请联系管理员！"
                                    };
                                }
                            }
                            break;
                        case 3:
                            if (controllerName == p.CONTROLLER)
                            {
                                if (actionName == p.ACTION)
                                {
                                    btnlist.Add(p.PERMISSION_CODE);
                                }
                            }
                            break;
                    }
                    // TempData.Btns = btnlist;
                    //设置按钮授权属性，然后赋值给ViewBag保存
                }
                ViewBag.Btns = JsonConvert.SerializeObject(btnlist);

            }

            //数据权限

            var DataRight= CommServers.GetDataRight(CurrentUser.USER_ID.ToString());
            Session["DataRight"] = true;


            //设置授权属性，然后赋值给ViewBag保存
            //ConvertAuthorizedInfo();
            // ViewBag.AuthorizeKey = AuthorizeKey;
            base.OnActionExecuting(filterContext);
        }


        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            //错误记录
           // WHC.Framework.Commons.LogTextHelper.Error(filterContext.Exception);

            // 当自定义显示错误 mode = On，显示友好错误页面
            if (filterContext.HttpContext.IsCustomErrorEnabled)
            {
                filterContext.ExceptionHandled = true;
                this.View("Error").ExecuteResult(this.ControllerContext);
            }
        }

        /// <summary>
        /// 对AuthorizeKey对象里面的操作权限进行赋值，用于页面判断
        /// </summary>
        protected virtual void ConvertAuthorizedInfo()
        {
            //判断用户权限
            //AuthorizeKey.CanInsert = HasFunction(AuthorizeKey.InsertKey);
            //AuthorizeKey.CanUpdate = HasFunction(AuthorizeKey.UpdateKey);
            //AuthorizeKey.CanDelete = HasFunction(AuthorizeKey.DeleteKey);
            //AuthorizeKey.CanView = HasFunction(AuthorizeKey.ViewKey);
            //AuthorizeKey.CanList = HasFunction(AuthorizeKey.ListKey);
            //AuthorizeKey.CanExport = HasFunction(AuthorizeKey.ExportKey);
        }


        /// <summary>
        /// 用于检查方法执行前的权限，如果未授权，返回MyDenyAccessException异常
        /// </summary>
        /// <param name="functionId"></param>
        protected virtual void CheckAuthorized(string functionId)
        {
            //if (!HasFunction(functionId))
            //{
            //    string errorMessage = "您未被授权使用该功能，请重新登录测试或联系管理员进行处理。";
            //    //throw new MyDenyAccessException(errorMessage);
            //}
        }
    }
}